package com.zwj.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zwj.Service.PersonService;
import com.zwj.pojo.Person;

import com.zwj.utils.ExportExcelUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;


import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by IntelliJ IDEA.
 *
 * @Author : 朱文杰
 * @create 2022/6/27 20:56
 */

@Controller
public class PersonController {

    @Autowired
    private PersonService personService;

    private static final Logger logger = LoggerFactory.getLogger(PersonController.class);

    private List<Person> people;

    //顾客列表
    @RequestMapping("/persons")
    public String persons(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "12") Integer pageSize, Model model) {

        PageHelper.startPage(pageNum, pageSize);

        try {
            List<Person> persons = personService.getPersonList();
            people = persons;
            model.addAttribute("persons", persons);//查询出的数据传到前端

            PageInfo pageInfo = new PageInfo(persons);//设置页面大小
            model.addAttribute("pageInfo", pageInfo);//将页面信息传到前端
        } finally {
            PageHelper.clearPage(); //清理 ThreadLocal 存储的分页参数,保证线程安全
        }
        return "person/list";
    }

    @RequestMapping("/person/toadd")
    public String toAddPerson() {
        return "person/add";
    }

    @RequestMapping("/person/add")
    public String addPerson(@RequestParam String pname, @RequestParam int psex, @RequestParam String ppid, @RequestParam String ptel, Model model) {
        Person flag = personService.getPersonByPpid(ppid);
        if (flag != null) {
            model.addAttribute("msg", "身份证信息已存在，该顾客已经办过卡了,卡号为:" + flag.getPid());
            return "person/add";
        } else {
            Person person = new Person(pname, psex, ppid, ptel);
            personService.addPerson(person);
            return "redirect:/persons";
        }
    }

    @RequestMapping("/person/delete/{pid}")
    public String deletePerson(@PathVariable("pid") int pid) {
        personService.deletePerson(pid);
        return "redirect:/persons";
    }

    @RequestMapping("/person/toupdate/{pid}")
    public String toUpdatePerson(@PathVariable("pid") int id, Model model) {
        Person person = personService.getPersonByPid(id);
        model.addAttribute("person", person);
        return "person/update";
    }

    @RequestMapping("/person/update")
    public String updatePerson(Person person, Model model) {
        Person flag = personService.getPersonByPpid(person.getPpid());
        if (flag != null && flag.getPid() != person.getPid()) {
            model.addAttribute("msg", "身份证信息已存在，该顾客已经办过卡了,卡号为:" + flag.getPid());
            return "person/update";
        } else {
            personService.updatePerson(person);
            return "redirect:/persons";
        }
    }

    @RequestMapping("/person/query")
    public String queryPerson(@RequestParam String pid, @RequestParam String pname, @RequestParam String ptel, @RequestParam String ppid, Model model) {

        if (pid.isEmpty()) {
            pid = null;
        }
        if (pname.isEmpty()) {
            pname = null;
        }
        if (ptel.isEmpty()) {
            ptel = null;
        }
        if (ppid.isEmpty()) {
            ppid = null;
        }
        HashMap map = new HashMap();
        map.put("pid", pid);
        map.put("pname", pname);
        map.put("ptel", ptel);
        map.put("ppid", ppid);

        List<Person> persons = personService.queryPerson(map);
        people = persons;
        model.addAttribute("persons", persons);

        return "person/querylist";
    }

    @RequestMapping("/exportSimpleExcel")
    public void exportSimpleExcel(HttpServletResponse response) {

        List<Map<String, String>> fieldList = new ArrayList<>();
        Map<String, String> field = new HashMap<>();
        field.put(ExportExcelUtils.FIELDNAME, "pid");
        field.put(ExportExcelUtils.FIELDZNAME, "会员卡号");
        fieldList.add(field);

        field = new HashMap<>();
        field.put(ExportExcelUtils.FIELDNAME, "pname");
        field.put(ExportExcelUtils.FIELDZNAME, "姓名");
        fieldList.add(field);

        field = new HashMap<>();
        field.put(ExportExcelUtils.FIELDNAME, "sex");
        field.put(ExportExcelUtils.FIELDZNAME, "性别");
        fieldList.add(field);

        field = new HashMap<>();
        field.put(ExportExcelUtils.FIELDNAME, "ppid");
        field.put(ExportExcelUtils.FIELDZNAME, "身份证号");
        fieldList.add(field);

        field = new HashMap<>();
        field.put(ExportExcelUtils.FIELDNAME, "ptel");
        field.put(ExportExcelUtils.FIELDZNAME, "联系方式");
        fieldList.add(field);

        Workbook workbook = ExportExcelUtils.dealWorkbook(getDatas(), fieldList);

        OutputStream out = null;
        try {
            String fileName = URLEncoder.encode("测试excel.xls", "UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            // 这句话的意思，是让浏览器用utf8来解析返回的数据
            response.setHeader("Content-type", "text/html;charset=UTF-8");
            //设置响应为excel
            response.setContentType("application/vnd.ms-excel");
            //将文件输出
            out = response.getOutputStream();
            workbook.write(out);
            out.flush();
        } catch (Exception e) {
            logger.error("response error ", e);
        } finally {
            IOUtils.closeQuietly(out);
        }

    }

    private List<Person> getDatas() {
        for (int i = 0; i < people.size(); i++) {
            if (people.get(i).getPsex() == 0) {
                people.get(i).setSex("女");
            } else {
                people.get(i).setSex("男");
            }
        }
        return people;
    }

}
